package com.cet.qz.unit01.chapter1_3;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @program: algorithm
 * @description: 用有限个栈实现一个队列   参考博客：https://www.cnblogs.com/dacc123/p/10574939.html
 * @author: 陈恩涛
 * @create: 2021-04-27 20:58
 **/
public class StackQueue1<Item> implements Iterable<Item> {

    /**
     * 负责出队
     */
    private Stack<Item> head;
    /**
     * 负责入队
     */
    private Stack<Item> tail;

    public StackQueue1() {
        head = new Stack<>();
        tail = new Stack<>();
    }

    public boolean isEmpty() {
        return head.isEmpty() && tail.isEmpty();
    }

    public int size() {
        return head.size() + tail.size();
    }

    public void enqueu(Item item) {
        tail.push(item);
    }

    public Item dequeue() {
        if (head.isEmpty()) {
            if (tail.isEmpty()) {
                throw new NoSuchElementException("队列为空！");
            }
            int size = tail.size();
            for (int i = 0; i < size(); i++) {
                head.push(tail.pop());
            }
        }
        return head.pop();
    }

    @Override
    public Iterator<Item> iterator() {
        return new StackQueueIterator();
    }

    class StackQueueIterator implements Iterator<Item> {

        private Iterator<Item> iterator;

        public StackQueueIterator() {
            Stack<Item> items = new Stack<>();
            for (Item item : tail) {
                items.push(item);
            }

            Stack<Item> temp = new Stack<>();
            for (Item item : head) {
                temp.push(item);
            }

            for (Item item : temp) {
                items.push(item);
            }
            iterator = items.iterator();
        }

        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Override
        public Item next() {
            return iterator.next();
        }

        @Override
        public void remove() {

        }
    }

    public static void main(String[] args) {
        StackQueue1<Integer> stackQueue1 = new StackQueue1<>();
        stackQueue1.enqueu(1);
        stackQueue1.enqueu(2);
        stackQueue1.enqueu(3);
        stackQueue1.forEach(System.out::println);

        System.out.println("===========");
        System.out.println(stackQueue1.dequeue());
    }

}

/**
 * 版本1.0,使用两个栈，一个head用于出栈，一个tail用于入栈，head为空将tail栈元素倒入head栈
 */
